﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using USERS.CYT369.COM.Models;

namespace USERS.CYT369.COM.Controllers
{
    //上传文章图片
    public partial class NewsController
    {
        private static Newtonsoft.Json.Linq.JObject m_FileConfiguration { get; set; }

        public NewsController()
        {
            var config = System.IO.File.ReadAllText(this.NewsFileConfig);

            

            m_FileConfiguration = Newtonsoft.Json.JsonConvert.DeserializeObject(config) as Newtonsoft.Json.Linq.JObject;
        }

        private string NewsFileConfig
        {
            get
            {
                string path = string.Empty;
                var dir = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).Directory;

                do
                {
                    if (System.IO.Directory.Exists(System.IO.Path.Combine(dir.FullName, "wwwroot")))
                    {
                        path = System.IO.Path.Combine(dir.FullName, @"wwwroot\js\news\news-file-config.json");
                        break;
                    }
                    dir = dir.Parent;
                } while (dir != null);

                return path;
            }
        }

        public ActionResult Controller()
        {
            string action = Request.Query.GetString("action");
            if (!string.IsNullOrEmpty(action))
            {
                switch (action)
                {
                    case "config":
                        return Config();

                    case "uploadimage":
                        return UploadImage();

                    case "uploadPreImage":
                        return UploadPreviewImage();

                    case "uploadscrawl":
                        return UploadScrawl();

                    case "uploadvideo":
                        return UploadVideo();

                    case "uploadfile":
                        return UploadFile();

                    case "catchimage":
                        return CatchImage();
                }
            }

            return DefaultJson(new
            {
                state = "请求地址出错"
            });
        }

        public ActionResult Config()
        {
            var config = System.IO.File.ReadAllText(this.NewsFileConfig);

            return Content(config);
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadImage()
        {
            var retVal = new ExecuteResult();
            long docId = Request.Form.GetLong("DocID", 0);
            int userId = Request.Form.GetInteger("UserID", 0);
            if (docId > 0 && Request.Form.Files.Count > 0)
            {
                var config = new UploadFileConfig()
                {
                    PathFormat = m_FileConfiguration.GetString("imagePathFormat"),
                    MaxSize = m_FileConfiguration.GetInteger("imageMaxSize"),
                    AllowFiles = m_FileConfiguration.GetArray<string>("imageAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
                    {
                        var tv = tk as Newtonsoft.Json.Linq.JValue;
                        if (tv != null && tv.Value != null)
                        {
                            return tv.Value.ToString();
                        }

                        return null;
                    })
                };

                var docFile = DoSaveFile(Request.Form.Files[0], config, userId, docId);
                if (docFile != null)
                {
                    retVal.Result = true;
                    retVal.Data = docFile;
                    retVal.Msg = "success";
                }
            }
            else
            {
                retVal.Msg = "参数错误";
            }

            return DefaultJson(retVal);
        }

        /// <summary>
        /// 预览图片上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadPreviewImage()
        {
            var retVal = new ExecuteResult();
            long docId = Request.Form.GetLong("DocID", 0);
            int userId = Request.Form.GetInteger("UserID", 0);
            if (docId > 0 && Request.Form.Files.Count > 0)
            {
                var config = new UploadFileConfig()
                {
                    PathFormat = m_FileConfiguration.GetString("imagePathFormat"),
                    MaxSize = m_FileConfiguration.GetInteger("imageMaxSize"),
                    AllowFiles = m_FileConfiguration.GetArray<string>("imageAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
                    {
                        var tv = tk as Newtonsoft.Json.Linq.JValue;
                        if (tv != null && tv.Value != null)
                        {
                            return tv.Value.ToString();
                        }

                        return null;
                    })
                };

                var docFile = DoSavePreviewFile(Request.Form.Files[0], config, userId, docId);
                if (docFile != null)
                {
                    retVal.Result = true;
                    retVal.Data = docFile;
                    retVal.Msg = "success";
                }
            }
            else
            {
                retVal.Msg = "参数错误";
            }

            return DefaultJson(retVal);
        }

        [HttpPost]
        public ActionResult UploadScrawl()
        {
            var retVal = new ExecuteResult();
            long docId = Request.Form.GetLong("DocID", 0);
            int userId = Request.Form.GetInteger("UserID", 0);

            if (docId > 0)
            {
                var config = new UploadFileConfig()
                {
                    PathFormat = m_FileConfiguration.GetString("scrawlPathFormat"),
                    MaxSize = m_FileConfiguration.GetInteger("scrawlMaxSize"),
                    AllowFiles = m_FileConfiguration.GetArray<string>("scrawlAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
                    {
                        var tv = tk as Newtonsoft.Json.Linq.JValue;
                        if (tv != null && tv.Value != null)
                        {
                            return tv.Value.ToString();
                        }

                        return null;
                    }),
                    oriName = "scrawl.png"
                };

                var file = new Base64File(this.Request, m_FileConfiguration.GetString("scrawlFieldName"));
                file.Name = config.oriName;

                var docFile = DoSaveFile(file, config, userId, docId, "base64");
                if (docFile != null)
                {
                    retVal.Result = true;
                    retVal.Data = docFile;
                    retVal.Msg = "success";
                }
            }
            else
            {
                retVal.Msg = "参数错误";
            }

            return DefaultJson(retVal);
        }

        [HttpPost]
        public ActionResult UploadVideo()
        {
            var retVal = new ExecuteResult();
            long docId = Request.Form.GetLong("DocID", 0);
            int userId = Request.Form.GetInteger("UserID", 0);

            if (docId > 0 && Request.Form.Files.Count > 0)
            {
                var config = new UploadFileConfig()
                {
                    PathFormat = m_FileConfiguration.GetString("videoPathFormat"),
                    MaxSize = m_FileConfiguration.GetInteger("videoMaxSize"),
                    AllowFiles = m_FileConfiguration.GetArray<string>("videoAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
                    {
                        var tv = tk as Newtonsoft.Json.Linq.JValue;
                        if (tv != null && tv.Value != null)
                        {
                            return tv.Value.ToString();
                        }

                        return null;
                    })
                };

                var docFile = DoSaveFile(Request.Form.Files[0], config, userId, docId);
                if (docFile != null)
                {
                    retVal.Result = true;
                    retVal.Data = docFile;
                    retVal.Msg = "success";
                }
            }
            else
            {
                retVal.Msg = "参数错误";
            }

            return DefaultJson(retVal);
        }

        [HttpPost]
        public ActionResult UploadFile()
        {
            var retVal = new ExecuteResult();
            long docId = Request.Form.GetLong("DocID", 0);
            int userId = Request.Form.GetInteger("UserID", 0);

            if (docId > 0 && Request.Form.Files.Count > 0)
            {
                var config = new UploadFileConfig()
                {
                    PathFormat = m_FileConfiguration.GetString("filePathFormat"),
                    MaxSize = m_FileConfiguration.GetInteger("fileMaxSize"),
                    AllowFiles = m_FileConfiguration.GetArray<string>("fileAllowFiles", delegate (Newtonsoft.Json.Linq.JToken tk)
                    {
                        var tv = tk as Newtonsoft.Json.Linq.JValue;
                        if (tv != null && tv.Value != null)
                        {
                            return tv.Value.ToString();
                        }

                        return null;
                    })
                };


                var docFile = DoSaveFile(Request.Form.Files[0], config, userId, docId);
                if (docFile != null)
                {
                    retVal.Result = true;
                    retVal.Data = docFile;
                    retVal.Msg = "success";
                }
            }
            else
            {
                retVal.Msg = "参数错误";
            }

            return DefaultJson(retVal);
        }

        [HttpPost]
        public ActionResult CatchImage()
        {
            return Content("");
        }

        public USERS.CYT369.COM.MODELS.Articles.DocAttachment DoSaveFile(Microsoft.AspNetCore.Http.IFormFile file, UploadFileConfig config, int userId, long docId, string type = "upload")
        {
            var now = DateTime.Now;
            string key = string.Format(config.PathFormat, userId, now.Year, now.Month, now.Day, docId, now.Ticks);

            switch (type)
            {
                case "remote":
                    break;

                case "base64":
                    {
                        var fileInfo = new System.IO.FileInfo(file.FileName);
                        if (CheckFile(config, fileInfo.Extension, file.Length))
                        {
                            key += fileInfo.Extension;
                        }

                        using (var stream = file.OpenReadStream())
                        {
                            if (USERS.CYT369.COM.UTILITY.OssClientService.Instance.SaveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket, key, stream))
                            {
                                var docFile = new USERS.CYT369.COM.MODELS.Articles.DocAttachment()
                                {
                                    DocID = docId,
                                    FileExtension = fileInfo.Extension,
                                    Name = fileInfo.Name,
                                    ImagePath = key,
                                };
                                if (docFile.Name != null && docFile.Name.Length > 128)
                                {
                                    docFile.Name = docFile.Name.Substring(docFile.Name.Length - 128, 128);
                                }
                                if (USERS.CYT369.COM.DAL.DocumentService.Instance.SaveDocAttachment(docFile))
                                {
                                    docFile.ImagePath = string.Format("{0}/{1}", USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket.HttpURL, key);
                                    return docFile;
                                }
                            }
                        }
                    }
                    break;

                default:
                    {
                        var fileInfo = new System.IO.FileInfo(file.FileName);
                        if (CheckFile(config, fileInfo.Extension, file.Length))
                        {
                            key += fileInfo.Extension;
                        }

                        using (var stream = file.OpenReadStream())
                        {
                            if (USERS.CYT369.COM.UTILITY.OssClientService.Instance.SaveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket, key, stream))
                            {
                                var docFile = new USERS.CYT369.COM.MODELS.Articles.DocAttachment()
                                {
                                    DocID = docId,
                                    FileExtension = fileInfo.Extension,
                                    Name = fileInfo.Name,
                                    ImagePath = key,
                                };
                                if (docFile.Name != null && docFile.Name.Length > 128)
                                {
                                    docFile.Name = docFile.Name.Substring(docFile.Name.Length - 128, 128);
                                }

                                if (USERS.CYT369.COM.DAL.DocumentService.Instance.SaveDocAttachment(docFile))
                                {
                                    docFile.ImagePath = string.Format("{0}/{1}", USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket.HttpURL, key);
                                    return docFile;
                                }
                            }
                        }
                    }
                    break;
            }

            return null;
        }

        public USERS.CYT369.COM.MODELS.Articles.DocAttachment DoSavePreviewFile(Microsoft.AspNetCore.Http.IFormFile file, UploadFileConfig config, int userId, long docId, string type = "upload")
        {
            var now = DateTime.Now;
            string key = string.Format(config.PathFormat, userId, now.Year, now.Month, now.Day, docId, now.Ticks);

            switch (type)
            {
                case "remote":
                    break;

                case "base64":
                    {
                        var fileInfo = new System.IO.FileInfo(file.FileName);
                        if (CheckFile(config, fileInfo.Extension, file.Length))
                        {
                            key += fileInfo.Extension;
                        }

                        using (var stream = file.OpenReadStream())
                        {
                            if (USERS.CYT369.COM.UTILITY.OssClientService.Instance.SaveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket, key, stream))
                            {
                                var docFile = new USERS.CYT369.COM.MODELS.Articles.DocAttachment()
                                {
                                    DocID = docId,
                                    FileExtension = fileInfo.Extension,
                                    Name = fileInfo.Name,
                                    ImagePath = key,
                                };

                                var imagePath = "";
                                if (USERS.CYT369.COM.DAL.DocumentService.Instance.UpdateDocumentPreviewImg(docId, key, ref imagePath))
                                {
                                    if (!string.IsNullOrEmpty(imagePath))
                                    {
                                        USERS.CYT369.COM.UTILITY.OssClientService.Instance.RemoveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket, imagePath);
                                    }

                                    docFile.ImagePath = string.Format("{0}/{1}", USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket.HttpURL, key);
                                    return docFile;
                                }
                            }
                        }
                    }
                    break;

                default:
                    {
                        var fileInfo = new System.IO.FileInfo(file.FileName);
                        if (CheckFile(config, fileInfo.Extension, file.Length))
                        {
                            key += fileInfo.Extension;
                        }

                        using (var stream = file.OpenReadStream())
                        {
                            if (USERS.CYT369.COM.UTILITY.OssClientService.Instance.SaveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket, key, stream))
                            {
                                var docFile = new USERS.CYT369.COM.MODELS.Articles.DocAttachment()
                                {
                                    DocID = docId,
                                    FileExtension = fileInfo.Extension,
                                    Name = fileInfo.Name,
                                    ImagePath = key,
                                };

                                var imagePath = "";
                                if (USERS.CYT369.COM.DAL.DocumentService.Instance.UpdateDocumentPreviewImg(docId, key, ref imagePath))
                                {
                                    if (!string.IsNullOrEmpty(imagePath))
                                    {
                                        USERS.CYT369.COM.UTILITY.OssClientService.Instance.RemoveFile(USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket, imagePath);
                                    }

                                    docFile.ImagePath = string.Format("{0}/{1}", USERS.CYT369.COM.UTILITY.SystemSettingService.Instance.NewsInternalBucket.HttpURL, key);
                                    return docFile;
                                }
                            }
                        }
                    }
                    break;
            }

            return null;
        }

        private bool CheckFile(UploadFileConfig config, string extension, long fileLength)
        {
            if (config.MaxSize.HasValue && fileLength > config.MaxSize)
            {
                throw new Exception("文件大小超出限制");
            }

            if (config.AllowFiles != null && string.IsNullOrEmpty(extension) == false)
            {
                if (!config.AllowFiles.Contains(extension.ToLower()))
                {
                    throw new Exception("文件类型不允许");
                }
            }

            return true;
        }



    }
}
